package middleware

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"strings"
	"zlxBook/common"
	"zlxBook/db"
	"zlxBook/model"
)

func Authmiddleware() gin.HandlerFunc {

	return func(context *gin.Context) {
		tokenstring := context.GetHeader("Authorization")
		fmt.Println(tokenstring)
		if tokenstring == "" || !strings.HasPrefix(tokenstring, "Bearer ") {
			context.JSON(http.StatusUnauthorized, gin.H{
				"msg": "未授权",
			})
			context.Abort()
			return
		}
		tokens := tokenstring[7:]
		token, claims, err := common.ParseToken(tokens)
		//解析
		if err != nil || !token.Valid {
			context.JSON(http.StatusUnauthorized, gin.H{"code": 401, "msg": "权限不够"})
			context.Abort()
			return
		}
		var user model.User
		db.DB.First(&user, claims.UserId)
		if user.ID == 0 {
			//找不到
			context.JSON(http.StatusUnauthorized, gin.H{"code": 401, "msg": "权限不够"})
			context.Abort()
			return
			//context.Abort()
		}
		//将user信息写入到context中去
		context.Set("user", user)
		context.Next()
	}

}
